import sys

import requests

from PySide6 import QtWidgets
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QLabel, QLineEdit, QListWidget


class Chushihua(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()
        self.token = ''
        main_widget = QtWidgets.QWidget()
        self.setCentralWidget(main_widget)
        self.setWindowTitle("创建项目")
        self.setGeometry(100, 100, 400, 300)

        # 创建三个页面
        self.login_widget = QtWidgets.QWidget()
        self.create_project_widget = QtWidgets.QWidget()
        self.audit_project_widget = QtWidgets.QWidget()
        self.init_ui()


    def init_ui(self):
        self.login_widget.setLayout(self.create_login_layout())
        self.create_project_widget.setLayout(self.create_create_project_layout())
        self.audit_project_widget.setLayout(self.create_audit_project_layout())
        self.stacked_widget = QtWidgets.QStackedWidget()
        self.stacked_widget.addWidget(self.login_widget)
        self.stacked_widget.addWidget(self.create_project_widget)
        self.stacked_widget.addWidget(self.audit_project_widget)
        self.setCentralWidget(self.stacked_widget)



    def create_login_layout(self):
        self.setWindowTitle("登录")
        self.server_url = QLabel("登录地址：")
        self.server_url_input = QLineEdit()
        self.server_url_input.setText("http://127.0.0.1:8080/login")

        self.label_username = QtWidgets.QLabel("用户名：")
        self.label_password = QtWidgets.QLabel("密码：")
        self.username = QtWidgets.QLineEdit()
        self.password = QtWidgets.QLineEdit()
        self.username.setText("admin")
        self.password.setText("rKxH189eNAx9wvY0CaVMpAoClgoIQmP6ZzoDmXRZlAO2MK1FHUC8/r0yDEXjj5HRjZ7YeaCyf7iOPvh9UuXToyUCt62emdNf9vdB6x2e5NqYTl55AFxLCZpENQaiMM5OC62fJ9tpPqe1bmD4UWsnN6t3RoB7Ibm1xl9mBQLcOB9/EOPGIQmiK2ERalHtXzDJmOvFgO1ZfCbbnlImVXP3EcOTZdpenGOuluVgq7my1d+vK/pB/FsVYDinjOOu1aRsGTZsXZIiA2EzOVXFgMIEa1R5BL2iOzm0YfxhWQz4wxLiPdQHLo92r7CUj2HldigQxa5xHs2Y4dztmiH8FzdXwQ==")
        self.login_button = QtWidgets.QPushButton("登录")
        self.login_button.clicked.connect(self.login)

        self.layout = QtWidgets.QGridLayout()
        self.layout.addWidget(self.server_url, 0, 0)
        self.layout.addWidget(self.server_url_input, 0, 1)

        self.layout.addWidget(self.label_username, 1, 0)
        self.layout.addWidget(self.username, 1, 1)
        self.layout.addWidget(self.label_password, 2, 0)
        self.layout.addWidget(self.password, 2, 1)
        self.layout.addWidget(self.login_button, 3, 1)
        return self.layout

    def create_create_project_layout(self):

        self.pro_url = QLabel("创建项目url：")
        self.pro_url_input = QLineEdit()
        self.pro_url_input.setText("http://127.0.0.1:8080/system/project")
        self.label_username = QtWidgets.QLabel("用户名：")
        self.label_password = QtWidgets.QLabel("密码：")
        self.label_company_name = QtWidgets.QLabel("公司名称：")
        self.label_project_name = QtWidgets.QLabel("项目名称：")
        self.label_project_type = QtWidgets.QLabel("项目类型：")
        self.label_project_key = QtWidgets.QLabel("项目关键词：")
        self.label_project_code = QtWidgets.QLabel("项目代码：")
        self.label_expire_date = QtWidgets.QLabel("过期时间：")
        self.conpany_name = QtWidgets.QLineEdit()
        self.project_name = QtWidgets.QLineEdit()
        # 创建 QListWidget
        self.listTypeWidget = QtWidgets.QListWidget()
        self.listTypeWidget.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection)

        # 项目类型列表
        project_type_list= [
            "PROJECT_TYPE_VIEXERGY",
            "PROJECT_TYPE_WATERMARK",
            "UNSPECIFIED",
            "PROJECT_TYPE_AUTONOMOUS_OPTIMIZATION_OPERATION_SYSTEM",
            "PROJECT_TYPE_COMMON",
            "PROJECT_TYPE_VISCADA",
            "PROJECT_TYPE_INDUSTRY",
            "PROJECT_TYPE_REGIONAL_POWER_DISTRIBUTION_NETWORK",
            "PROJECT_TYPE_BASIC",
            "PROJECT_TYPE_SECONDARY_NETWORK",
            "PROJECT_TYPE_EMS",
            "PROJECT_TYPE_CIVIL"
        ]

        # 添加项目到 QListWidget
        for item in project_type_list:
            item_widget = QtWidgets.QListWidgetItem(item)
            item_widget.setFlags(item_widget.flags() | Qt.ItemFlag.ItemIsUserCheckable | Qt.ItemFlag.ItemIsEnabled)
            item_widget.setCheckState(Qt.CheckState.Unchecked)
            self.listTypeWidget.addItem(item_widget)

        self.project_key = QtWidgets.QLineEdit()
        self.project_code = QtWidgets.QLineEdit()
        self.expire_date = QtWidgets.QLineEdit()
        self.expire_date.setText("2099-12-31")

        self.create_project_button = QtWidgets.QPushButton("创建项目")
        self.create_project_button.clicked.connect(self.create_project)
        self.pro_layout = QtWidgets.QGridLayout()
        self.pro_layout.addWidget(self.pro_url, 0, 0)
        self.pro_layout.addWidget(self.pro_url_input, 0, 1)
        self.pro_layout.addWidget(self.label_company_name, 1, 0)
        self.pro_layout.addWidget(self.conpany_name, 1, 1)
        self.pro_layout.addWidget(self.label_project_name, 2, 0)
        self.pro_layout.addWidget(self.project_name, 2, 1)
        self.pro_layout.addWidget(self.label_project_type, 3, 0)
        self.pro_layout.addWidget(self.listTypeWidget, 3, 1)
        self.pro_layout.addWidget(self.label_project_key, 4, 0)
        self.pro_layout.addWidget(self.project_key, 4, 1)
        self.pro_layout.addWidget(self.label_project_code, 5, 0)
        self.pro_layout.addWidget(self.project_code, 5, 1)
        self.pro_layout.addWidget(self.label_expire_date, 6, 0)
        self.pro_layout.addWidget(self.expire_date, 6, 1)
        self.pro_layout.addWidget(self.create_project_button, 7, 1)

        return self.pro_layout

    def create_audit_project_layout(self):

        self.audit_label = QtWidgets.QLabel("审核项目id:")
        self.audit_id = QtWidgets.QLineEdit()
        self.audit_url = QLabel("审核项目url：")
        self.audit_url_input = QLineEdit()
        self.audit_url_input.setText("http://127.0.0.1:8080/system/project/audit")
        self.audit_button = QtWidgets.QPushButton("审核项目")
        self.audit_button.clicked.connect(self.audit_project)
        self.layout_audit = QtWidgets.QGridLayout()
        self.layout_audit.addWidget(self.audit_label, 0, 0)
        self.layout_audit.addWidget(self.audit_id, 0, 1)
        self.layout_audit.addWidget(self.audit_url, 1, 0)
        self.layout_audit.addWidget(self.audit_url_input, 1, 1)
        self.layout_audit.addWidget(self.audit_button, 2, 1)
        return self.layout_audit



    def login(self):
        username = self.username.text()
        password = self.password.text()
        server_url = self.server_url_input.text()
        url = server_url
        data = {"username": username, "password": password,"from": "backend"}
        headers = {"Content-Type": "application/json",
                   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.41"
                   }
        try:
            response = requests.post(url, json=data, headers=headers)
        except requests.exceptions.RequestException as e:
            QtWidgets.QMessageBox.warning(self, "警告", "连接失败！"+ str(e))
            return
        if response.status_code == 200:
            if response.json().get("code") == 200:
                token = response.json().get("data").get("token")
                print(token)
                self.token = token
                QtWidgets.QMessageBox.information(self, "提示", "登录成功！token：" + f"{token}")
                charge = QtWidgets.QMessageBox.question(self, "提示", "是否创建项目？是，创建；否，审核", QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No)
                if charge == QtWidgets.QMessageBox.StandardButton.Yes:
                    self.setWindowTitle("创建项目")
                    self.stacked_widget.setCurrentIndex(1)
                else:
                    self.setWindowTitle("审核项目")
                    self.stacked_widget.setCurrentIndex(2)
            else:
                QtWidgets.QMessageBox.warning(self,"错误",response.json().get("msg"))

        else:
            QtWidgets.QMessageBox.warning(self, "警告", "登录失败！连接状态码："+str(response.status_code))

    def create_project(self):
        if not self.token:
            QtWidgets.QMessageBox.warning(self, "警告", "请先登录！")
            return
        company_name = self.conpany_name.text()
        project_name = self.project_name.text()
        # 获取所有被选中的项
        selected_items = []
        for index in range(self.listTypeWidget.count()):
            item = self.listTypeWidget.item(index)
            if item.checkState() == Qt.CheckState.Checked:
                selected_items.append(item.text())
        project_type = ",".join(selected_items)
        if not project_type:
            QtWidgets.QMessageBox.warning(self, "警告", "请选择项目类型！")
            return
        print(project_type)
        project_key = self.project_key.text()
        project_code = self.project_code.text()
        pro_url = self.pro_url_input.text()
        url = pro_url
        expire_date = self.expire_date.text()

        data = {"sysProject": {"companyName": company_name, "projectName": project_name, "projectType": project_type,
                "projectKey": project_key, "projectCode": project_code,"expireDate": expire_date,"projectId": project_code}}
        headers = {"Content-Type": "application/json",
                   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.41",
                   "Authorization": f"Bearer {self.token}"
                   }
        response = requests.post(url, json=data, headers=headers)
        print(response.json())
        if response.status_code == 200:
            if response.json().get("code") == 200:
                QtWidgets.QMessageBox.information(self, "提示", "创建成功！")
                self.stacked_widget.setCurrentIndex(2)
            else:
                QtWidgets.QMessageBox.warning(self,"错误",response.json().get("msg"))
        else:
            QtWidgets.QMessageBox.warning(self, "警告", "创建失败！连接状态码："+str(response.status_code))

    def audit_project(self):
        if not self.token:
            QtWidgets.QMessageBox.warning(self, "警告", "请先登录！")
            return
        audit_id = self.audit_id.text()
        audit_url = self.audit_url_input.text()
        url = audit_url
        data = {"sysProject": {"projectId": audit_id, "status": "PAID"}}
        headers = {"Content-Type": "application/json",
                   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.41",
                   "Authorization": f"Bearer {self.token}"
                   }
        response = requests.post(url, json=data, headers=headers)
        print(response.json())
        if response.status_code == 200:
            if response.json().get("code") == 200:
                QtWidgets.QMessageBox.information(self, "提示", "审核成功！")
            else:
                QtWidgets.QMessageBox.warning(self,"错误",response.json().get("msg"))

        else:
            QtWidgets.QMessageBox.warning(self, "警告", "审核失败！连接状态码："+str(response.status_code))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Chushihua()
    window.show()
    sys.exit(app.exec())